import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:rapid_kit/rapid_kit.dart';
import '../../theme.dart';
import '../../utils/lifecycle_aware.dart';
import '../../utils/snack_tips.dart';
import '../../widgets/global_widgets.dart';

/// 固件升级-demo自带-未使用
class FirmwarePage extends StatefulWidget {
  final String deviceId;

  const FirmwarePage({super.key, required this.deviceId});

  @override
  State<FirmwarePage> createState() => _FirmarePageState();
}

class _FirmarePageState extends LifecycleAwareState<FirmwarePage> {
  late String _deviceId;
  FirmwareVersion? _firmwareVersion;

  FirmwareStatePolling? _firmwareStatePolling;

  bool _polling = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildTitleBar(context),
      body: _buildRootBody(context),
    );
  }

  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      title: const Text('固件升级', style: TextStyle(color: SampleThemeConfigure.colorPrimary)),
      backgroundColor: SampleThemeConfigure.colorBackground,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: SampleThemeConfigure.colorPrimary),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      elevation: 0,
    );
  }

  Widget _buildRootBody(BuildContext context) {
    final available = _firmwareVersion?.available?.version?.isNotEmpty == true;
    return Stack(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            _buildRoundedRectangleWithIconAndText(icon: Icons.numbers, text: "固件ID： ${_firmwareVersion?.current?.id ?? ""}"),
            _buildRoundedRectangleWithIconAndText(icon: Icons.info, text: "版本号： ${_firmwareVersion?.current?.version ?? "Unknown"}"),
            GestureDetector(
              onTap: () async => _onPerformUpgrade(),
              child: _buildRoundedRectangleWithIconAndText(
                  icon: Icons.upcoming_sharp,
                  text: available ? "有新版本，点击升级！\n新版本 ${_firmwareVersion?.available?.version}：${_firmwareVersion?.available?.description}" : "已是最新版本",
                  textColor: const Color.fromRGBO(4, 145, 49, 1)),
            )
          ],
        ),
        if (_polling)
          Positioned.fill(
            child: Container(
              color: Colors.black54,
              child: Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    createCenterLoading(color: Colors.white, size: 20),
                    const SizedBox(height: 16),
                    const Text(
                      "升级中",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
      ],
    );
  }

  void _onPerformUpgrade() async {
    final available = _firmwareVersion?.available?.version?.isNotEmpty == true;
    if (!available) return;

    final resp = await FirmwareService.performUpgrade(_deviceId, _firmwareVersion?.available?.version ?? "");

    if (!mounted) return;
    if (resp.success) {
      SnackTips.show(context, "触发成功");
      _firmwareStatePolling?.stop();
      _firmwareStatePolling = FirmwareStatePolling.create(_deviceId, _firmwareVersion?.available?.version ?? "");
      _firmwareStatePolling?.listener = (ret) {
        if (ret.success) {
          SnackTips.show(context, "升级成功");
          setState(() {
            _polling = false;
          });
          _load();
        } else {
          SnackTips.show(context, "升级失败: ${ret.code} ${ret.message}");
        }
      };
      _firmwareStatePolling?.start();
      setState(() {
        _polling = true;
      });
    } else {
      SnackTips.show(context, "${resp.message}");
    }
  }

  Widget _buildRoundedRectangleWithIconAndText(
      {required IconData icon, required String text, Color textColor = SampleThemeConfigure.colorTextPrimary}) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
      padding: const EdgeInsets.all(16.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.0),
      ),
      child: Row(
        children: <Widget>[
          Icon(icon, color: SampleThemeConfigure.colorPrimary),
          const SizedBox(width: 20),
          Text(
            text,
            style: TextStyle(color: textColor),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId;
    _load();
  }

  @override
  void dispose() {
    super.dispose();

    _firmwareStatePolling?.stop();
  }

  void _load() async {
    final resp = await FirmwareService.queryCurrentVersion(_deviceId);
    if (!mounted) return;
    if (resp.success) {
      setState(() {
        _firmwareVersion = resp.data;
      });
    } else {
      SnackTips.show(context, "Faild: ${resp.code} ${resp.message}");
    }
  }
}
